package com.tanhua.manage.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.*;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.CommentApi;
import com.tanhua.dubbo.api.mongo.PublishApi;
import com.tanhua.dubbo.api.mongo.VideoApi;
import com.tanhua.manage.domain.Freeze;
import com.tanhua.manage.domain.UnFreeze;
import com.tanhua.manage.mapper.FreezeMapper;
import com.tanhua.manage.mapper.UnFreezeMapper;
import com.tanhua.manage.utils.RelativeDateFormat;
import org.apache.dubbo.config.annotation.Reference;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.*;

@Service
public class UserService {
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private VideoApi videoApi;
    @Reference
    public PublishApi publishApi;
    @Reference
    private CommentApi commentApi;
    @Autowired
    private FreezeMapper freezeMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private UnFreezeMapper unFreezeMapper;


    /**
     * 接口名称：用户数据翻页
     */
    public ResponseEntity<Object> findByPage(Integer page, Integer pagesize) {
        // 调用Api服务，查询用户信息
        IPage<UserInfo> iPage = userInfoApi.findByPage(page, pagesize);
        // 封装分页对象
        PageResult pageResult = new PageResult(page, pagesize, (int) iPage.getTotal(), iPage.getRecords());
        return ResponseEntity.ok(pageResult);
    }

    /**
     * 接口名称：用户基本资料
     */
    public ResponseEntity<Object> findById(Long userId) {
        UserInfo userInfo = userInfoApi.findById(userId);
        return ResponseEntity.ok(userInfo);
    }

    /**
     * 接口名称：视频记录翻页
     */
    public ResponseEntity<Object> videoList(Long uid, Integer page, Integer pagesize) {
        //1. 调用Api分页查询
        PageResult pageResult = videoApi.findByPage(page, pagesize, uid);
        //2. 获取小视频集合
        List<Video> videoList = (List<Video>) pageResult.getItems();
        //3. 封装vo
        List<VideoVo> voList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(videoList)) {
            for (Video video : videoList) {
                //3.1 创建vo、封装vo
                VideoVo vo = new VideoVo();
                vo.setId(video.getId().toString());

                // 根据用户id查询
                UserInfo userInfo =
                        userInfoApi.findById(video.getUserId());
                if (userInfo != null) {
                    BeanUtils.copyProperties(userInfo, vo);
                }
                // 封装vo: video--->vo
                BeanUtils.copyProperties(video, vo);
                // 封装vo的其他属性（没有与Video对应上的）
                vo.setCover(video.getPicUrl());
                vo.setSignature(video.getText());
                vo.setHasFocus(0);
                vo.setHasLiked(0);

                //3.2 添加到集合
                voList.add(vo);
            }
        }
        //4. 把封装好的vo集合设置到分页对象中、返回
        pageResult.setItems(voList);
        return ResponseEntity.ok(pageResult);
    }

    /**
     * 接口名称：动态分页
     */
    public ResponseEntity<Object> findPublishList(Integer page, Integer pagesize, Long uid, Integer state) {
        // 根据用户id查询动态

        PageResult pageResult = publishApi.findByPage(page, pagesize, uid, state);
        this.setMovementsVo(pageResult);
        return ResponseEntity.ok(pageResult);
    }

    private void setMovementsVo(PageResult pageResult) {
        //3. 获取分页中的动态数据
        List<Publish> publishList = (List<Publish>) pageResult.getItems();
        //4. 封装返回的vo集合
        List<MovementsVo> voList = new ArrayList<>();
        //5. 遍历动态集合publishList, 封装voList
        if (publishList != null && publishList.size() > 0) {
            for (Publish publish : publishList) {
                // 创建vo对象
                MovementsVo vo = new MovementsVo();
                this.convertPublishToMovements(publish, vo);
                // 把封装好的vo添加到集合
                voList.add(vo);
            }
        }

        // 把处理好的vo集合设置到分页对象中
        pageResult.setItems(voList);
    }

    // 工具类：把publish转换为MovementsVo对象
    private void convertPublishToMovements(Publish publish, MovementsVo vo) {
        // 根据用户id查询
        UserInfo userInfo = userInfoApi.findById(publish.getUserId());
        if (userInfo != null) {
            BeanUtils.copyProperties(userInfo, vo);
            if (userInfo.getTags() != null) {
                vo.setTags(userInfo.getTags().split(","));
            }
        }
        // 对象拷贝：publish-->vo
        BeanUtils.copyProperties(publish, vo);

        // 设置动态id、动态的图片
        vo.setId(publish.getId().toString());
        vo.setImageContent(publish.getMedias().toArray(new String[]{}));

        // 设置距离
        vo.setDistance("50米");
        // 设置时间如：5小时之前
        vo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(publish.getCreated())));

        vo.setHasLiked(0);
        vo.setHasLoved(0);

    }

    /**
     * 接口名称：动态详情
     */
    public ResponseEntity<Object> findMovementsById(String publishId) {
        // 根据动态id查询
        Publish publish = publishApi.findById(publishId);
        // 创建返回的vo对象
        MovementsVo vo = new MovementsVo();
        // publish--->vo
        this.convertPublishToMovements(publish,vo);
        return ResponseEntity.ok(vo);
    }

    /**
     * 接口名称：评论列表翻页
     */
    public ResponseEntity<Object> findCommentsById(
            String publishId, Integer page, Integer pagesize) {
        //1. 分页查询评论
        PageResult pageResult = commentApi.findByPage(publishId, page, pagesize);
        //2. 获取评论数据
        List<Comment> list = (List<Comment>) pageResult.getItems();
        //3. 定义返回的vo集合
        List<CommentVo> voList = new ArrayList<>();
        //4. 封装数据 list--->voList
        if (!CollectionUtils.isEmpty(list)) {
            for (Comment comment : list) {
                CommentVo vo = new CommentVo();
                vo.setId(comment.getId().toString());
                // 根据用户id查询
                UserInfo userInfo = userInfoApi.findById(comment.getUserId());
                vo.setAvatar(userInfo.getAvatar());
                vo.setNickname(userInfo.getNickname());
                vo.setContent(comment.getContent());
                vo.setCreateDate(new DateTime(comment.getCreated()).toString("yyyy年MM月dd日 HH:mm"));
                vo.setLikeCount(0);
                vo.setHasLiked(0);

                voList.add(vo);
            }
        }
        //5. 设置到分页对象中
        pageResult.setItems(voList);
        return ResponseEntity.ok(pageResult);
    }

    public ResponseEntity<Object> savefreeze(Map<String, Object> param) {
        Integer userId = (Integer) param.get("userId");
        String freezingTime = (String) param.get("freezingTime");
        String freezingRange = (String) param.get("freezingRange");
        String reasonsForFreezing = (String) param.get("reasonsForFreezing");
        String frozenRemarks = (String) param.get("frozenRemarks");
        Freeze freeze = new Freeze(userId,Integer.valueOf(freezingTime),Integer.valueOf(freezingRange),reasonsForFreezing,frozenRemarks);
        QueryWrapper<Freeze> wrapper=new QueryWrapper<>();
        wrapper.eq("id",userId).eq("freezing_range",freezingRange);
        //查询这个用户同类型的冻结状态是否存在，存在的话修改时间
        Freeze one = freezeMapper.selectOne(wrapper);
        if(one==null){
            freezeMapper.insert(freeze);
        }else{
            one.setFreezingTime(Integer.valueOf(freezingTime));
            freezeMapper.updateById(one);
        }
        //通过freezingtime设置redis中的有效期
        switch (Integer.valueOf(freezingTime)){
            case 1:setFreeze(userId,3l,Integer.valueOf(freezingRange));
            break;
            case 2:setFreeze(userId,7l,Integer.valueOf(freezingRange));
            break;
            case 3:setFreeze(userId,365l,Integer.valueOf(freezingRange));
            break;
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setUserStatus("2");
        userInfo.setId(userId.longValue());
        userInfoApi.update(userInfo);
        HashMap<String, String> map = new HashMap<>();
        map.put("message","冻结成功");
        return ResponseEntity.ok(map);
    }

    public ResponseEntity<Object> unfreeze(Map<String, Object> param) {
        //获取前端传过来的消息
        Integer userId = (Integer) param.get("userId");
        String frozenRemarks = (String) param.get("frozenRemarks");
        //把要userInfo表中的状态改为1
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId.longValue());
        userInfo.setUserStatus("1");
        userInfoApi.updateByUserId(userInfo);
        //删除冻结表的数据
        QueryWrapper<Freeze> wrapper=new QueryWrapper<>();
        wrapper.eq("id",userId);
        freezeMapper.delete(wrapper);
        //解冻记录表的记录新增
        UnFreeze unFreeze = new UnFreeze();
        unFreeze.setFrozenRemarks(frozenRemarks);
        unFreeze.setUserId(userId.longValue());

        unFreezeMapper.insert(unFreeze);
        //redis中删除冻结的key
        String key="Freeze_"+"Id_"+userId+"_Type_";
        Set<String> keys = redisTemplate.keys(key + "*");
        redisTemplate.delete(keys);
        HashMap<String, String> map = new HashMap<>();
        map.put("message","解冻成功");
        return ResponseEntity.ok(map);
    }

    /**
     *
     * @param userId 用户id
     * @param time   冻结的天数
     * @param freezingRange  冻结的类型
     */
    private void setFreeze(Integer userId,Long time,Integer freezingRange){
        //Freeze_Id_1_Type_1 userinfo id为1的用户被冻结了3天，冻结的功能为登录
        String key="Freeze_"+"Id_"+userId+"_Type_"+freezingRange;
        if(time==365l){
            redisTemplate.opsForValue().set(key,freezingRange+"");
        }else {
            redisTemplate.opsForValue().set(key,freezingRange+"", Duration.ofDays(time));
        }


    }

    public ResponseEntity<Object> findPubulish(Integer page, Integer pagesize, Long uid, String state) {
        PageResult pageResult=publishApi.findByPublishList(page,pagesize,uid,state);
        List<Publish> publishList = (List<Publish>) pageResult.getItems();
        ArrayList<PublishVo> voList = new ArrayList<>();
        if(publishList!=null){
            for (Publish publish : publishList) {
                if(publish!=null&&publish.getUserId()!=null){
                    PublishVo publishVo = new PublishVo();
                    BeanUtils.copyProperties(publish,publishVo);
                    UserInfo userInfo = userInfoApi.findById(publish.getUserId());
                    BeanUtils.copyProperties(userInfo,publishVo);
                    publishVo.setImageContent(publish.getMedias().toArray(new String[]{}));
                    voList.add(publishVo);
                }

            }
        }
        pageResult.setItems(voList);
        return ResponseEntity.ok(pageResult);
    }

    public ResponseEntity<Object> publishPass(String[] id) {
        publishApi.publishPass(id);
        HashMap<String, String> map = new HashMap<>();
        map.put("message","审核成功");
        return ResponseEntity.ok(map);
    }

    public ResponseEntity<Object> publishUnPass(String[] id) {
        publishApi.publishUnPass(id);
        HashMap<String, String> map = new HashMap<>();
        map.put("message","审核成功");
        return ResponseEntity.ok(map);
    }
}



















